package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.PracticeBrushTeacher;
import com.xmy.cultivate.entity.SenateScoreSet;
import com.xmy.cultivate.entity.Shopping;
import com.xmy.cultivate.respons.ClassesNum;
import com.xmy.cultivate.respons.ResSchoolDate;
import com.xmy.cultivate.service.ISenateScoreSetService;
import com.xmy.cultivate.service.ISubjectsService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 教务获取积分设置 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-10-24
 */
@RestController
@RequestMapping("/api/senateScoreSet")
public class SenateScoreSetController extends BaseController {

    @Autowired
    ISenateScoreSetService iSenateScoreSetService;

    @Autowired
    ISubjectsService iSubjectsService;

    @GetMapping("")
    public Result findAllPage(@RequestParam(value = "pageNum", defaultValue = "-1", required = false) Integer pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "-1", required = false) Integer pageSize,
                              @RequestParam(value = "export", defaultValue = "0", required = false) Integer export,
                              @RequestParam(value = "yearPart", required = false) String yearPart,
                              @RequestParam(value = "quarterNum", required = false) String quarterNum,
                              @RequestParam(value = "gradeSection", required = false) String gradeSection,
                              @RequestParam(value = "subjectsId", required = false) String subjectsId,
                              @RequestParam(value = "yearClassId", required = false) String yearClassId) throws IOException {
        IPage<SenateScoreSet> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.select("*,getDictName( senate_project_id,28 ) AS project_name");
        wrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        wrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);

        StringBuilder yearClassConditions = new StringBuilder();
        if (StringUtils.isNotBlank(yearClassId)) {
            List<String> labelIdList = Arrays.asList(yearClassId.split(","));
            for (String strItem : labelIdList) {
                if (yearClassConditions.length() > 0) {
                    yearClassConditions.append(" OR ");
                }
                yearClassConditions.append("FIND_IN_SET('").append(strItem).append("', year_class_id)");
            }
            if (yearClassConditions.length() > 0) {
                wrapper.apply(" (" + yearClassConditions + ") ");
            }
        }

        StringBuilder subjectsConditions = new StringBuilder();
        if (StringUtils.isNotBlank(subjectsId)) {
            List<String> labelIdList = Arrays.asList(subjectsId.split(","));
            for (String strItem : labelIdList) {
                if (subjectsConditions.length() > 0) {
                    subjectsConditions.append(" OR ");
                }
                subjectsConditions.append("FIND_IN_SET('").append(strItem).append("', subjects_id)");
            }
            if (subjectsConditions.length() > 0) {
                wrapper.apply(" (" + subjectsConditions + ") ");
            }
        }

        StringBuilder gradeSectionConditions = new StringBuilder();
        if (StringUtils.isNotBlank(gradeSection)) {
            List<String> labelIdList = Arrays.asList(gradeSection.split(","));
            for (String strItem : labelIdList) {
                if (gradeSectionConditions.length() > 0) {
                    gradeSectionConditions.append(" OR ");
                }
                gradeSectionConditions.append("FIND_IN_SET('").append(strItem).append("', grade_section)");
            }
            if (gradeSectionConditions.length() > 0) {
                wrapper.apply(" (" + gradeSectionConditions + ") ");
            }
        }

        iSenateScoreSetService.page(iPage, wrapper);

        if (export == 1) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("教务积分");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setFontHeightInPoints((short) 11);
            headerCellStyle.setFont(headerFont);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Row headerRow = sheet.createRow(0);
            sheet.createFreezePane(0, 1);// 冻结首行

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFont(headerFont);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            List<String> headList = new ArrayList<>();
            headList.add("年份");
            headList.add("学期");
            headList.add("学段/年级");
            headList.add("科目");
            headList.add("项目名称");
            headList.add("率/数量");
            headList.add("数值");
            headList.add("积分");

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            int rowIndex = 1;// 数据行起始索引

            for (SenateScoreSet scoreSet : iPage.getRecords()) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(scoreSet.getYearPart());
                sheet.setColumnWidth(0, 15 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(CommonUtil.getQuarterNameForId(scoreSet.getQuarterNum()));
                sheet.setColumnWidth(1, 15 * 256);
                cell2.setCellStyle(cellStyle);

                StringBuffer yearClassIdSb = new StringBuffer();
                Cell cell3 = row.createCell(2);
                if (scoreSet.getStageType() == 1) {
                    if (StringUtils.isNotBlank(scoreSet.getGradeSection())) {
                        String[] sections = scoreSet.getGradeSection().split(",");
                        for (String section : sections) {
                            if (section.equals("0")) {
                                yearClassIdSb.append("少儿");
                            } else if (section.equals("1")) {
                                yearClassIdSb.append("小学");
                            } else if (section.equals("2")) {
                                yearClassIdSb.append("初中");
                            } else if (section.equals("3")) {
                                yearClassIdSb.append("高中");
                            }
                            if (!section.equals(sections[sections.length - 1])) {
                                yearClassIdSb.append("、");
                            }
                        }
                        yearClassId = yearClassIdSb.toString();
                    }
                } else if (scoreSet.getStageType() == 2) {
                    if (StringUtils.isNotBlank(scoreSet.getYearClassId())) {
                        String[] sections = scoreSet.getYearClassId().split(",");
                        for (String section : sections) {
                            if (section.equals("0")) {
                                yearClassIdSb.append("幼儿园");
                            } else if (section.equals("1")) {
                                yearClassIdSb.append("一年级");
                            } else if (section.equals("2")) {
                                yearClassIdSb.append("二年级");
                            } else if (section.equals("3")) {
                                yearClassIdSb.append("三年级");
                            } else if (section.equals("4")) {
                                yearClassIdSb.append("四年级");
                            } else if (section.equals("5")) {
                                yearClassIdSb.append("五年级");
                            } else if (section.equals("6")) {
                                yearClassIdSb.append("六年级");
                            } else if (section.equals("7")) {
                                yearClassIdSb.append("七年级");
                            } else if (section.equals("8")) {
                                yearClassIdSb.append("八年级");
                            } else if (section.equals("9")) {
                                yearClassIdSb.append("九年级");
                            } else if (section.equals("10")) {
                                yearClassIdSb.append("高一");
                            } else if (section.equals("11")) {
                                yearClassIdSb.append("高二");
                            } else if (section.equals("12")) {
                                yearClassIdSb.append("高三");
                            }
                            if (!section.equals(sections[sections.length - 1])) {
                                yearClassIdSb.append("、");
                            }
                        }
                        yearClassId = yearClassIdSb.toString();
                    }
                }
                cell3.setCellValue(yearClassId);
                sheet.setColumnWidth(2, 100 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(3);
                if (scoreSet.getSubjectsId() != null) {
                    cell4.setCellValue(iSubjectsService.getById(scoreSet.getSubjectsId()).getName());
                }
                sheet.setColumnWidth(3, 15 * 256);
                cell4.setCellStyle(cellStyle);

                Cell cell6 = row.createCell(4);
                cell6.setCellValue(scoreSet.getProjectName());
                sheet.setColumnWidth(4, 30 * 256);
                cell6.setCellStyle(cellStyle);

                Cell cell7 = row.createCell(5);
                if (scoreSet.getStatisticsType() == 1) {
                    cell7.setCellValue("率");
                } else if (scoreSet.getStatisticsType() == 2) {
                    cell7.setCellValue("数量");
                }
                sheet.setColumnWidth(5, 20 * 256);
                cell7.setCellStyle(cellStyle);

                Cell cell8 = row.createCell(6);
                if (scoreSet.getStatisticsType() == 1) {
                    cell8.setCellValue(scoreSet.getStatisticsCount() + "%");
                } else if (scoreSet.getStatisticsType() == 2) {
                    cell8.setCellValue(scoreSet.getStatisticsCount().toString());
                }
                sheet.setColumnWidth(6, 20 * 256);
                cell8.setCellStyle(cellStyle);

                Cell cell9 = row.createCell(7);
                cell9.setCellValue(scoreSet.getIntegral());
                sheet.setColumnWidth(7, 20 * 256);
                cell9.setCellStyle(cellStyle);

            }

            String fileName = "教务管理导出" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
        }

        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    @PostMapping()
    public Result save(@RequestBody SenateScoreSet senateScoreSet) {

        iSenateScoreSetService.saveOrUpdate(senateScoreSet);

        return new Result(Code.SAVE_OK, "", Code.SAVE_OK_MSG);
    }

    @DeleteMapping("")
    public Result deleteTask(@RequestParam(value = "id") String id) {
        SenateScoreSet senateScoreSet = iSenateScoreSetService.getById(id);
        if (Objects.isNull(senateScoreSet)) {
            return new Result(Code.EXP_ERROR, null, "该数据不存在");
        }
        iSenateScoreSetService.removeById(id);
        return new Result(Code.DELETE_OK, null, Code.DELETE_OK_MSG);
    }


}
